import React, { useState, useEffect } from 'react'
import WangEditor from '../../components/WangEditor/WangEditor'
import Card from '../../components/Card/Card'
import User from '../../components/User/User'
import axios from '../../axios'
import Pagination from '../../components/Pagination/Pagination'
import { getUser } from '../../utils/storage'
import Button from '../../components/Button/Button'
import './guestbook.scss'

export default function Guestbook() {
  const [content, setContent] = useState('')
  const [list, setList] = useState([])
  const [pageSize] = useState(10)
  const [pageIndex, setPageIndex] = useState(1)
  const [total, setTotal] = useState(0)

  const submit = () => {
    if (content === '<p><br></p>') {
      alert('留言不能为空')
    } else {
      axios.post('/guestbook', {
        user: getUser()._id,
        content
      }).then(res => {
        setList([res.data, ...list])
        setContent('')
      })
    }
  }

  const changePageIndex = (index) => {
    setPageIndex(index)
  }

  useEffect(() => {
    axios.get('/guestbook', {
      pageIndex,
      pageSize
    }).then(res => {
      setList(res.data.records)
      setTotal(res.data.total)
    })
  }, [pageIndex, pageSize])

  return (
    <div className='guestbook'>
      <WangEditor disabled={getUser()._id ? false : true} content={content} getHtml={setContent} />
      <Button onClick={submit} style={{ marginTop: '10px', marginBottom: '30px'}}>留言</Button>
      <div className='list'>
        {
          list?.length ?
          list.map(item => {
            return (
              <Card className='card' key={item._id} style={{maxHeight: '800px', overflowY: 'auto'}}>
                <User style={{marginBottom: '10px'}} avatar={item.user.avatar} nickname={item.user.nickname}></User>
                <div className='content' dangerouslySetInnerHTML={{ __html: item.content }}></div>
              </Card>
            )
          })
          : 
          <div style={{marginTop: '20px'}}>还没有留言！</div>
        }
      </div>
      <Pagination current={pageIndex} pageSize={pageSize} total={total} change={changePageIndex}></Pagination>
    </div>
  )
}
